package com.kancy.mybatisplus.generator.idea.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.kancy.mybatisplus.generator.config.Settings;
import com.kancy.mybatisplus.generator.idea.service.ApplicationService;
import com.kancy.mybatisplus.generator.log.Log;
import com.kancy.mybatisplus.generator.view.Main;
import com.kancy.mybatisplus.generator.view.model.ModuleComboBoxModel;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Objects;

/**
 * <p>
 * MybatisplusCodeGeneratorAction
 * <p>
 *
 * @author: kancy
 * @date: 2020/6/15 11:37
 **/

public class MybatisplusCodeGeneratorAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        ApplicationManager.getApplication().invokeLater(() -> {
            if (!ApplicationService.getInstance().initService()){
                return;
            }
            Project project = e.getProject();
            Settings.setDefaultWorkPath(project.getBasePath());
            Module[] modules = ModuleManager.getInstance(e.getProject()).getModules();
            Main app = ApplicationService.getInstance().getApp();
            app.getComboBox_module().removeAllItems();
            for (int i = 0; i < modules.length; i++) {
                Module module = modules[i];
                File parentFile = FileUtils.getFile(module.getModuleFilePath()).getParentFile();
                ModuleComboBoxModel.ItemData data = new ModuleComboBoxModel.ItemData(module.getName(),
                        Objects.equals(parentFile.getName(),".idea") ?
                                parentFile.getParentFile().getAbsolutePath() : parentFile.getAbsolutePath());
                if (i == 0){
                    data.setSelected(true);
                    app.getComboBox_module().addItem(data);
                    app.getComboBox_module().setSelectedItem(data);
                }else {
                    app.getComboBox_module().addItem(data);
                }
            }
            ApplicationService.getInstance().display();
        });
    }

}
